# /usr/bin/python3
# coding=utf-8

import pytest
from utils.requests_helper import RequestUtil
from utils.mysql_helpper import MySQLPlugin
from config.setting import *
from utils.logger_helpper import logger


@pytest.fixture(scope="session", autouse=True)
def auth_token():
    """获取认证token"""
    userId = User_Id

    # 发送获取token的请求
    reqObj = RequestUtil(
        base_url=Test_URL
    )
    method = 'get'
    params = {'userId': userId}

    try:
        response = reqObj.send_request(method, endpoint=Auth_URL, params=params)
        if response.status_code == 200:
            token = response.json().get('data', {})
            # logger.debug(f"Token Info: {token}")
        return token
    except Exception as e:
        # logger.error(f"获取token失败: {str(e)}")
        pytest.fail(f"获取token失败: {str(e)}")


@pytest.fixture(scope="session", autouse=True)
def api_client(auth_token: str):
    """创建带有认证token的请求客户端"""

    # 完成请求头的设置
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f"Bearer {auth_token}"
    }

    # 创建客户端实例
    client = RequestUtil(
        base_url=Test_URL,
        default_headers=headers,
        timeout=30
    )

    yield client

    # 测试结束后可以在这里添加清理逻辑
    logger.debug("测试结束，清理请求客户端")


def pytest_sessionfinish(session):
    """修正后的测试结果统计"""
    # 获取终端报告器
    reporter = session.config.pluginmanager.get_plugin('terminalreporter')

    # 统计实际失败数（排除标记允许失败的用例）
    actual_failures = 0
    if reporter:
        actual_failures = len(reporter.stats.get('failed', []))

    logger.debug(f"实际失败用例数: {actual_failures}")
    # 设置退出码（保留原始退出码逻辑）
    session.exitstatus = 1 if actual_failures == 0 else 1


@pytest.fixture(scope="session", autouse=True)
def mysql_client():
    config = {
        "host": DB_Host,
        "user": DB_User,
        "password": DB_Pwd,
        "port": DB_Port,
        "database": DB_Schema,
    }
    client = MySQLPlugin(config=config)
    yield client
    # 测试结束后可以在这里添加清理逻辑
    client.close()
    logger.debug("测试结束，关闭所有数据库连接池")